<?php

namespace app\api\controller;

use app\api\model\CodeModel;
use app\api\model\ConfigModel;
use app\api\model\MoneyLogModel;
use app\api\model\UserModel;
use app\api\model\UserSign;
use app\api\model\UserTask;
use app\api\model\WorkModel;
use app\BaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use think\response\Json;

//use think\Db;

class Index extends BaseController
{
    /**
     * @return Json
     * @author duyang
     */
    public function register(): Json
    {
        //接收参数
        $data = $this->request->get();
        $userModel = new UserModel();
        $codeModel = new CodeModel();
        //验证邀请码
        $code = $codeModel->where('name', $data['code'])->where('status', 1)->find();
        $info = $userModel->where('username', $data['mobile'])->find();
        if ($info) {
            $this->error('用户已存在');
        }
        if (!$code) {
            $this->error('邀请码错误');
        }
        try {
            $id = $userModel->register($data['mobile'], $data['password']);
            $codeModel->where('name', $data['code'])->update(['status' => 0]);
        } catch (\Exception $e) {
            $this->error('注册失败', $e->getMessage());
        }
        $data = $userModel->JWT($id);
        $userModel->where('id', $id)->update(['ip' => $this->request->ip()]);
        $info = $userModel->where('id', $id)->find();
        $this->success('注册成功', ['userInfo' => $info, 'token' => $data]);
    }

    /**
     * @return Json
     * 登录
     */
    public function login(): Json
    {
        $data = $this->request->post();
        $userModel = new UserModel();
        $info = $userModel->where('username', $data['mobile'])->find();
//        halt($info->id);
        if (!$info) {
            $this->error('用户不存在');
        }
        if ($info['password'] != $data['password']) {
            $this->error('密码错误');
        }
        $data = $userModel->JWT($info->id);
        $this->success('登录成功', ['userInfo' => $info, 'token' => $data]);
    }

    /**
     * 获取任务列表
     * */
    public function getWorkList()
    {
        $workModel = new WorkModel();
        $data = $workModel->with('user')->where('status', '=', 1)
            ->order('createtime', 'desc')
            ->select()
            ->toArray();
        $this->success('获取成功', $data);
    }

    /**
     * @return Json
     * 领取任务
     */
    public function receiveTask(): Json
    {
        $data = $this->request->get();
        $workInfo = WorkModel::where('id', $data['work_id'])->find();
        if (!$workInfo) {
            $this->error('任务不存在');
        }
        $taskInfo = UserTask::where('work_id', $data['work_id'])
            ->where('user_id', $this->user_id)
            ->where('status', '<>', 3)
            ->find();
//        halt($taskInfo['user_id']);
        if ($taskInfo) {
            $this->error('已有进行中任务！', $taskInfo);
        }
        $userTask = new UserTask();
        //开启事务
        Db::startTrans();
        try {
//            WorkModel::where('id', $data['work_id'])->update(['status' => 0]);
            $userTask->addTask($this->user_id, $data['work_id'], $workInfo['user_id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('领取失败', $e->getMessage());
        }
        $this->success('领取成功!');
    }

    /**
     * 获取我的任务记录
     * */
    public function getTaskList()
    {
        $status = $this->request->get('status', 1);
        $userTask = new UserTask();
        $data = UserTask::where('user_id', $this->user_id)
            ->where('status', $status)
            ->with(['taskRecord', 'user'])
            ->order('createtime', 'desc')
            ->select()->toArray();
        $this->success('获取成功', $data);
    }

    /**
     * 获取我的审核任务记录
     * */
    public function getVerifyList()
    {
        $data = UserTask::where('pid', $this->user_id)
            ->where('status', 2)
            ->with(['taskRecord', 'user'])
            ->order('createtime', 'desc')
            ->select()->toArray();
        foreach ($data as &$item) {
            $item['image'] = json_decode($item['image'], true);
//            dump($item['image']);
        }
        $this->success('获取成功', $data);
    }

    /**
     * 任务详情
     */
    public function workDetail()
    {
        $id = $this->request->get('work_id');
        $workModel = new WorkModel();
        $data = $workModel->where('id', $id)->find();
        $this->success('获取成功', $data);
    }

    /**
     * 完成任务（上传截图）
     * */
    public function finishWork()
    {
        $data = $this->request->post();
//        halt($data['img']);
        $userTask = new UserTask();
        $info = $userTask->where('id', $data['id'])->find();
        if (!$info) {
            $this->error('任务不存在');
        }
        if ($info['status'] != 1) {
            $this->error('任务已完成');
        }
        if ($data['img'] == "[]") {
            $this->error('请上传截图');
        }
        try {
            $userTask->where('id', $data['id'])->update(['status' => 2, 'updatetime' => time(), 'image' => $data['img']]);
        } catch (\Exception $e) {
            $this->error('完成失败');
        }
        $this->success('任务完成,等待审核');
    }

    /**
     *审核任务
     * */
    public function checkTask()
    {
        $data = $this->request->post();
        $userTask = new UserTask();
        $userModel = new UserModel();
        $moneyLog = new MoneyLogModel();
        $info = $userTask->where('id', $data['task_id'])->find();
        $workInfo = WorkModel::where('id', $info['work_id'])->find();
//        halt($workInfo);
        if (!$info) {
            $this->error('任务不存在');
        }
        if ($info['status'] != 2) {
            $this->error('任务已审核');
        }
        $afterMoney = $userModel->where('id', $this->user_id)->field('bonus')->find();
//        $this->success('',$afterMoney['bonus']);
        $beforMoney = $afterMoney['bonus'] + $data['value'];
        try {
            $userModel->money($info['user_id'], $workInfo['money']);
            $moneyLog->log($this->user_id, '+' . $data['value'], $afterMoney['bonus'], $beforMoney, '完成任务获得呜噜');
            $userTask->where('id', $data['task_id'])->update(['status' => 3, 'ratevalue' => $data['rateValue'], 'updatetime' => time()]);
        } catch (\Exception $e) {
            $this->error('审核失败', $e->getMessage());
        }
        $this->success('审核成功', $data);
    }

    public function getMoney()
    {
        $money = UserModel::where('id', $this->user_id)->field('bonus')->find();
        $this->success('获取成功', $money);
    }

    public function getMoneyLog()
    {
        $data = MoneyLogModel::where('user_id', $this->user_id)->order('createtime', 'desc')->select();
        $this->success('获取成功', $data);
    }

    public function getTaskCount()
    {
        $count = UserTask::where('user_id', $this->user_id)->where('status', 1)->count();
        $this->success('获取成功', $count);
    }

    public function getVerifyCount()
    {
        $count = UserTask::where('pid', $this->user_id)->where('status', 2)->count();
        $this->success('获取成功', $count);
    }

    /**
     * 更新头像资料
     * */
    public function updateUserInfo()
    {
        $data = $this->request->post();
        //处理性别
        if ($data['sex'] == "女") {
            $data['sex'] = 0;
        } else {
            $data['sex'] = 1;
        }
        $userModel = new UserModel();
        $userModel->where('id', $this->user_id)->update($data);
        $this->success('更新成功');
    }

    public function updateBack()
    {
        $backImg = $this->request->post('backimg');
        $userModel = new UserModel();
        $data = $userModel->where('id', $this->user_id)->update(['backimg'=> $backImg]);
        $this->success('切换成功', $data);
    }

    /**
     * 获取用户信息
     * */

    public function getUserInfo()
    {
        $userModel = new UserModel();
        $data = $userModel->where('id', $this->user_id)->find();
        //处理性别
        if ($data['sex'] == 1) {
            $data['sex'] = "男";
        } else {
            $data['sex'] = "女";
        }
        $this->success('获取成功', $data);
    }

    /**
     * 签到
     * */

    public function sign()
    {
        $userModel = new UserModel();
        $userSignModel = new UserSign();
        $singData = $userSignModel->where('user_id', $this->user_id)
            ->field('user_id,signtime')
            ->order('signtime', 'desc')
            ->find();
        $userModel = new UserModel();
        $moneyLog = new MoneyLogModel();
        $signDay = $userModel->where('id', $this->user_id)->field('signday')->find();
        $afterMoney = $userModel->where('id', $this->user_id)->field('bonus')->find();
//        $this->success('',$afterMoney['bonus']);
        $beforMoney = $afterMoney['bonus'] + 5;
        //签到时间
        if (!empty($singData) && date('Y-m-d') === $singData['signtime']) {
            $this->error('今日已签到!');
        }
        $configModel = new ConfigModel();
        $configData = $configModel->where('name', 'sign')->find();
        Db::startTrans();
        try {
            UserSign::create([
                'user_id' => $this->user_id,
                'signtime' => date('Y-m-d'),
                'createtime' => time()
            ]);
            $userModel->where('id', $this->user_id)->inc('signday', 1)->update();
            $moneyLog->log($this->user_id, '+' . $configData['value'], $afterMoney['bonus'], $beforMoney, '每日签到获得呜噜');
            $userModel->money($this->user_id, 5);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('签到失败', $e->getMessage());
        }
        $this->success('签到成功', $signDay);
    }

    public function getSign()
    {
        $userSignModel = new UserSign();
        $singData = $userSignModel->where('user_id', $this->user_id)
            ->field('user_id,signtime')
            ->order('signtime', 'desc')
            ->find();
        $userModel = new UserModel();
        $signDay = $userModel->where('id', $this->user_id)->field('signday')->find();
//        halt($signDay);
        //签到时间
        if (!empty($singData) && date('Y-m-d') === $singData['signtime']) {
            $this->error('今日已签到!', $signDay);
        }
        $this->success('可以签到', $signDay);
    }

    /**
     * 发布任务
     * */

    public function addWork()
    {
        $data = $this->request->post();
        $workModel = new WorkModel();
        if (empty($data['title'])) {
            $this->error('标题不能为空');
        } else if (empty($data['content'])) {
            $this->error('内容不能为空');
        }
        try {
            $workModel->create([
                'user_id' => $this->user_id,
                'order_id' => 'task' . rand(10000, 99999),
                'type' => 1,
                'money' => $data['money'],
                'title' => $data['title'],
                'content' => $data['content'],
                'data_statr' => date("Y-m-d H:i:s", time()),
                'data_end' => date("Y-m-d H:i:s", time() + $data['time'] * 60),
                'createtime' => time()
            ]);
        } catch (\Exception $e) {
            $this->error('发布失败');
        }
        $this->success('发布成功');
    }

    /**
     * 上传图片
     * */
    public function upload()
    {
        $file = $_FILES['file'];
        $extension = substr($file['name'], strrpos($file['name'], '.') + 1);
        $path = $file['tmp_name'];
//        halt($extension);
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = "MXLREcC35mfL9YboRK3bPInQllas_pj2WV-qkMoF";
        $secretKey = "jL85KCOnOOkQOCNmjPPh_Swl6njCfQKrLwlyj2Oe";
        $bucket = "wudixiaoyang";
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = $path;
        // 上传到存储后保存的文件名
        $key = uniqid() . time() . '.' . $extension;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的  putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile
        ($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');
        $data = 'http://qiniu.gaowa.love/' . $key;
        return json(['code' => 1, 'msg' => '上传成功', 'data' => $data]);
//        $this->success('上传成功',$data);
    }
}